package com.hdw.job.controller;

import com.hdw.common.base.BaseException;
import com.hdw.common.db.DynamicDataSource;
import com.hdw.common.db.HikariDataSourceExt;
import com.hdw.common.util.DBUtil;
import com.hdw.common.util.DateUtil;
import com.hdw.common.util.EtlUtil;
import com.hdw.common.util.SnowflakeIdWorker;
import com.hdw.common.vo.DataExecParamVO;
import com.hdw.common.vo.LayMsg;
import com.hdw.job.api.EtlBaseService;
import com.hdw.job.api.EtlRunService;
import com.hdw.job.api.EtlTaskOdsService;
import com.hdw.job.bean.model.EtlHandlerExec;
import com.hdw.job.constant.JobConstant;
import com.hdw.job.mapper.EtlHandlerExecMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * Created by liujunlei on 2021/5/21.
 */
@RestController
@RequestMapping("/etl/runJob/")
@Api(tags = "任务运行")
@CrossOrigin(origins = "*", maxAge = 3600)
public class RunJobController {
    @Autowired
    EtlTaskOdsService etlTaskOdsService;
    @Autowired
    EtlBaseService etlBaseService;
    @Autowired
    EtlRunService etlRunService;
    @Autowired
    EtlHandlerExecMapper etlHandlerExecMapper;

    @ApiOperation(value = "校验SQL")
    @RequestMapping(value = "testSql", method = RequestMethod.GET)
    public LayMsg testSql(String SQL, String idDbSou) {
        HikariDataSourceExt souDataSource = DynamicDataSource.getHikariDataSourceById(idDbSou);
        if (souDataSource == null) return LayMsg.fail().addMsg(String.format("数据源获取失败，ID[%s]", idDbSou));
        Connection connection = null;
        ResultSet resultSet = null;
        try {
            connection = souDataSource.getConnection();
            String qSQL = EtlUtil.buildSql(SQL, new Date(), new Date(), souDataSource.getEuTp());
            qSQL = qSQL.replaceAll(" where ", " where 1 = 2 and ");
            qSQL = qSQL.replaceAll(" WHERE ", " WHERE 1 = 2 AND ");
            resultSet = DBUtil.testQuery(connection, qSQL);
        } catch (Exception e) {
            e.printStackTrace();
            return LayMsg.fail().addMsg(e.getMessage());
        } finally {
            DBUtil.closeDBResources(resultSet, null, connection);
        }
        return LayMsg.success().addMsg("执行成功");
    }

    @ApiOperation(value = "手工执行任务")
    @RequestMapping(value = "jobExecByHand", method = RequestMethod.GET)
    public LayMsg jobExecByHand(String startDate, String endDate, String idTasks,String type) throws BaseException{
        if (StringUtils.isEmpty(startDate)) return LayMsg.fail().addMsg("缺少开始时间");
        if (StringUtils.isEmpty(endDate)) return LayMsg.fail().addMsg("缺少结束时间");
        if (StringUtils.isEmpty(idTasks)) return LayMsg.fail().addMsg("没有选择要执行的任务");
        String[] split = idTasks.split(",");
        List<DataExecParamVO> list = null;
        startDate = startDate.replaceAll("-","");
        endDate = endDate.replaceAll("-","");
        if(JobConstant.JOB_TYPE_ODS.equals(type) || JobConstant.JOB_TYPE_DIM.equals(type)) {
            list = etlTaskOdsService.findParamVOS(Arrays.asList(split),startDate,endDate);
        } else if(JobConstant.JOB_TYPE_XXLJOB.equals(type)) {

        }
        Long groupId = SnowflakeIdWorker.getId();
        if(list!=null && list.size()>0) {
            EtlHandlerExec exec = new EtlHandlerExec();
            exec.setDtBegin(new Date());
            exec.setDes(type+"["+startDate+"~"+endDate+"]");
            exec.setIdGroup(groupId);
            exec.setStatus("STARTING");
            exec.setEuTp(type);
            etlHandlerExecMapper.insertReturnId(exec);
            etlRunService.runBatchJobList(list,groupId,JobConstant.JOB_EXE_TYPE_MANUAL);
            while (!etlRunService.isGroupEnd(groupId)) {
                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            exec.setDtEnd(new Date());
            exec.setStatus(etlRunService.getStatus(groupId));
            exec.setTimes((exec.getDtEnd().getTime()-exec.getDtBegin().getTime())/1000);
            etlHandlerExecMapper.updateByPrimaryKeySelective(exec);
        }
        return LayMsg.success().addMsg("执行完毕");
    }

    private LayMsg validExecBefore(String startDate, String endDate, String idTasks) {
        if (StringUtils.isEmpty(startDate)) return LayMsg.fail().addMsg("缺少开始时间");
        if (StringUtils.isEmpty(endDate)) return LayMsg.fail().addMsg("缺少结束时间");
        if (StringUtils.isEmpty(idTasks)) return LayMsg.fail().addMsg("没有选择要执行的任务");

        Date start = DateUtil.toDateByFormat(startDate, "yyyy-MM-dd");
        if (start == null) return LayMsg.fail().addMsg("开始时间格式错误");
        Date end = DateUtil.toDateByFormat(endDate, "yyyy-MM-dd");
        if (end == null) return LayMsg.fail().addMsg("结束时间格式错误");
        return LayMsg.success();
    }

    @ApiOperation(value = "获取执行中的任务列表")
    @RequestMapping(value = "findHandlerExec", method = RequestMethod.GET)
    public LayMsg findHandlerExec(String jobType) {
        EtlHandlerExec exec = new EtlHandlerExec();
        exec.setEuTp(jobType);
        List<EtlHandlerExec> execList = etlHandlerExecMapper.findByModelOrderByDate(exec);
        return LayMsg.success().addData(execList);
    }
}